var app = require('express')();
app.get('/', function(req, res){
	var now=new Date();
	res.end(now.toString());
});

app.get('/save', function(req, res){
	try{
		var storage = new global.ACESDK.STORAGE('flowers');
		storage.putObject({
			  Key: 'wxh.txt',                            
			  Body: 'shanghai',
			  ContentType: 'text/plain',  
			  ContentEncoding: 'utf-8', 
			  Expires:60000
			},
			function (err, data) {
			  if (err) {
				res.end('错误:'+err.message);
			  }
			  else{
				res.end('put 成功:'+JSON.stringify(data));
			  }
			}
		);
	}
	catch(err){
	   res.end(err.message);
	}
});

app.get('/rank', function(req, res){
	try{
		var storage = new global.ACESDK.STORAGE('flowers');
		storage.getObject(
			{Key:'wxh.txt'},
			function(err,data){
				if (err){
					console.log(err);
					res.end(err.message+"============not found");
				}
				else{
					console.log('========wxh get success');
					res.end(JSON.stringify(data));
				}
			}
		);
	}
	catch(err){
	   res.end(err.message);
	}
});

app.get('/getRanks', function(req, res){
	try{
		var mysql = require('mysql');
		var connection = mysql.createConnection({
			host     : 'rdsv02iey739p2ca9s42.mysql.rds.aliyuncs.com',
			user     : 'rjaiwip80m7il31h',
			password : 'wxh2003yhp',
			database : 'rjaiwip80m7il31h'
		});
		 
		connection.connect();
		 
		connection.query(
		    " select distinct r1.userID,cast(r1.score/r1.cellCount as DECIMAL(18,4)) as score,"+
			"   concat(cast(r1.score as char),'/',cast(r1.cellCount as char)) as scoreFormula"+
			' from ranks as r1,'+
			' (select userID,max(cast(score/cellCount as DECIMAL(18,4))) as maxScore'+
			'  from ranks'+
			'  group by userID) as r2'+
			' where r1.userID=r2.userID and (cast(r1.score/r1.cellCount as DECIMAL(18,4)))=r2.maxScore'+
			' order by r2.maxScore desc'+
			' limit 10',			
			function(err, rows, fields) {
				if (err){
					res.end(err.message);
				}
				else{
					res.end(JSON.stringify(rows));
				}
			}
		);
		
		connection.end();
	}
	catch(err){
	   res.end(err.message);
	}
});

app.get('/saveScore', function(req, res){
	try{
		var mysql = require('mysql');
		var connection = mysql.createConnection({
			host     : 'rdsv02iey739p2ca9s42.mysql.rds.aliyuncs.com',
			user     : 'rjaiwip80m7il31h',
			password : 'wxh2003yhp',
			database : 'rjaiwip80m7il31h'
		});
		 
		connection.connect();		
		
		connection.query('insert into ranks(userID,cellCount,score,saveTime) values(?,?,?,?)',
			[req.query.userID,req.query.cellCount,req.query.score,new Date()], 
			function(err, rows, fields) {
				if (err){
					res.end(err.message);
				}
				else{
					res.end('ok');
				}
			}
		);
		
		connection.end();
	}
	catch(err){
	   res.end(err.message);
	}
});

var server = app.listen(0, function() {
    console.log('Express server started on port %s', server.address().port);
});